//
//  AppDelegate.m
//  Remind
//
//  Created by mac on 17/9/27.
//  Copyright © 2017年 2017.09.27. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "ViewController.h"
#import "LeftMenuViewController.h"
#import "LGSideMenuController.h"
#import <UserNotifications/UserNotifications.h>
#import "DataCach.h"
#import "Date.h"

@interface AppDelegate () <UNUserNotificationCenterDelegate>
{
    
}
@property (strong, nonatomic) LGSideMenuController *sideMenuCon;
@property (strong, nonatomic) UNUserNotificationCenter *center;
@property (copy, nonatomic) NSMutableArray *notificationIDArr;
@property (assign, nonatomic) NSInteger badges;

@end

@implementation AppDelegate

- (void)loadView{
    _leftSideMenuIdx = 0;
    MainViewController *mainVC = [[MainViewController alloc] init];
    
    ViewController *vc = [[ViewController alloc] init];
    
    UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:mainVC];
    
    LeftMenuViewController *leftMenu = [LeftMenuViewController new];
    
    _sideMenuCon = [LGSideMenuController sideMenuControllerWithRootViewController:navCon leftViewController:leftMenu rightViewController:nil];
    _sideMenuCon.leftViewWidth = [UIScreen mainScreen].bounds.size.width - 100;
    _sideMenuCon.leftViewPresentationStyle = LGSideMenuPresentationStyleSlideBelow;
    _sideMenuCon.leftViewSwipeGestureRange = LGSideMenuSwipeGestureRangeMake(10.0, 10.0);
    
    self.shadownView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.shadownView.backgroundColor = [UIColor blackColor];
    self.shadownView.alpha = 0.0;
    
    AppDelegate * __weak me = self;
    _sideMenuCon.willShowLeftView = ^(LGSideMenuController * _Nonnull sideMenuController, UIView * _Nonnull view) {
        UINavigationController *nav = (UINavigationController *) me.sideMenuCon.rootViewController;
        UIViewController *VCon = nav.viewControllers.firstObject;
        [VCon.view addSubview:me.shadownView];
        LeftMenuViewController *left = (LeftMenuViewController *)sideMenuController.leftViewController;
        left.idx = me.leftSideMenuIdx;
        [left.tableView reloadData];
        [UIView transitionWithView:me.shadownView duration:0.2 options:UIViewAnimationOptionTransitionNone animations:^{
            me.shadownView.alpha = 0.5;
        } completion:nil];
    };
    
    _sideMenuCon.willHideLeftView = ^(LGSideMenuController * _Nonnull sideMenuController, UIView * _Nonnull view) {
        [UIView transitionWithView:me.shadownView duration:0.2 options:UIViewAnimationOptionTransitionNone animations:^{
            me.shadownView.alpha = 0.0;
        } completion:^(BOOL finished) {
            if(finished) [me.shadownView removeFromSuperview];
        }];
    };
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = _sideMenuCon;
    [self.window makeKeyAndVisible];
}

#pragma mark - 推送消息
- (void)sendNotificationMassage:(NSDictionary *)dict{
    NSString *msg = [dict objectForKey:@"event"];
    NSDate *toDate = [Date strToDate:[dict objectForKey:@"date"] Formatter:@"yyyy-MM-dd-HH:mm"];
    //减去3600秒即一个小时，提前通知
    NSTimeInterval time = [Date BetweenDateAndTime:[NSDate date] toDate:toDate] - 3600;
    
    if([_notificationIDArr containsObject:msg]) return ;
    if(time < 0) return ;
    if(!_sendNotifiction) return ;
    
    [_notificationIDArr addObject:msg];
    //创建一个推送内容
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"提示" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:[msg stringByAppendingString:@"时间到了"] arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    //content.badge = @(1);
    
    // 在设定时间后推送本地推送
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time repeats:NO];
    
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:msg content:content trigger:trigger];
    
    //添加推送成功后的处理
    //AppDelegate __weak *me = self;
    [_center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if(!error){
            NSLog(@"推送成功%@",dict);
            //[me.center removeAllDeliveredNotifications];
        }
    }];
}

#pragma mark - UserNotificationCenter代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    // 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    _badges++;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:_badges];
    completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound + UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    //当用户点击了推送通知后会调用这个方法,移除已经推送过的通知
    [_center removeAllDeliveredNotifications];
    _badges--;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:_badges];
    completionHandler();
    
}

#pragma makr - APPDelegate代理方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self loadView];
    //判断用户是否开启推送
    NSString *bol = [DataCach getValueByClassName:@"sendNotific"];
    if(!bol) bol = @"0";
    _sendNotifiction = [bol boolValue];
    
    _badges = 0;
    [application setApplicationIconBadgeNumber:0];
    _notificationIDArr = [NSMutableArray new];
    
    _center = [UNUserNotificationCenter currentNotificationCenter];
    _center.delegate = self;
    
    //删除已推送的通知和未推送的通知
    [_center removeAllDeliveredNotifications];
    [_center removeAllPendingNotificationRequests];
    
    if([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0){
        UNAuthorizationOptions types = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
        [_center requestAuthorizationWithOptions:types completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
                if(granted){
                    NSLog(@"注册成功");
                
                    [_center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                        if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined)
                        {
                            NSLog(@"未选择");
                        }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                            NSLog(@"未授权");
                        }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                            NSLog(@"已授权");
                        }
                    }];
                }
            
        }];
//        NSDictionary *dict = @{
//                               @"date":@"2017-11-06-16:00",
//                               @"event":@"时间到了"
//                               };
//        [self sendNotificationMassage:dict];
//        [self sendNotificationMassage:dict];
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
